#include "texture.h"

namespace SkyID
{

//- Texture -------------------------------------------------------------------

Texture::Texture() :
	mID(0), mWidth(0), mHeight(0), mFormat(0), mTarget(0)
{
	//
}

Texture::Texture(const Image *image, GLint clampMode) :
	mID(0), mWidth(0), mHeight(0), mFormat(0), mTarget(0)
{
	setValid(create(image, clampMode));
}

Texture::~Texture()
{
	if (mID)
        glDeleteTextures(1, &mID);
}

bool Texture::create(const Image *image, GLint clampMode)
{
	LOG_ASSERT(image && image->isValid());
	setValid(false);

	if (mID)
		glDeleteTextures(1, &mID);

	glGenTextures(1, &mID);
	if (!mID)
	{
		LOG_MSG("Texture: failed to generate texture id");
		return false;
	}

	mTarget = GL_TEXTURE_2D;

	glBindTexture(mTarget, mID);
	glTexParameteri(mTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(mTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(mTarget, GL_TEXTURE_WRAP_S, clampMode);
	glTexParameteri(mTarget, GL_TEXTURE_WRAP_T, clampMode);
	//glTexParameteri(mTarget, GL_TEXTURE_WRAP_R, clampMode); // do we need this?

	mWidth = image->getWidth();
	mHeight = image->getHeight();
	mFormat = image->getFormat()==FORMAT_RGB ? GL_RGB : GL_RGBA;

	glTexImage2D(mTarget, 0, mFormat, mWidth, mHeight, 0,
		mFormat, GL_UNSIGNED_BYTE, image->getData());

	if (glGetError() != GL_NO_ERROR)
	{
		glDeleteTextures(1, &mID);
		LOG_MSG("Texture: failed to create texture (e.g. non power of two)");
		return false;
	}

	setValid(true);
	return true;
}

} // namespace SkyID
